package com.hydra.base.utils;

import com.hydra.base.common.Constant;
import com.hydra.base.error.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import reactor.util.annotation.NonNull;

import javax.servlet.http.HttpServletRequest;

/**
 * 获取Spring容器的Bean对象的工具类
 * @Author Hydra
 * @Date 2022/3/17 18:05
 */
@Slf4j
@Component
public class SpringUtils implements ApplicationContextAware  {

    protected static ApplicationContext CONTEXT;

    @Override
    public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
        CONTEXT = applicationContext;
    }

    /**获取请求里面带的平台数据*/
    public static String getPlatform(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        String platform = request.getHeader("platform");
        //为空则默认是web平台
        if(StringUtil.isBlank(platform)){
            platform = Constant.USER_PLATFORM.WEB;
        }
        return platform;
    }


    /**获取请求里面带的系统编号*/
    public static String getSystemCode(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        String systemCode = request.getHeader("systemCode");
        //为空则默认是通用系统
        if(StringUtil.isBlank(systemCode)){
            systemCode = Constant.SystemCode.DEFAULT;
        }
        return systemCode;
    }

    public static Object getBean(String name) throws BeansException {
        if (null == CONTEXT) {
            throw new BusinessException("The application context is null, please check.");
        } else {
            return CONTEXT.getBean(name);
        }
    }

    public static <T> T getBean(Class<T> requiredType) throws BeansException {
        if (null == CONTEXT) {
            throw new BusinessException("The application context is null, please check.");
        } else {
            return CONTEXT.getBean(requiredType);
        }
    }

    public static <T> T getBean(String name, Class<T> requiredType) throws BeansException {
        if (null == CONTEXT) {
            throw new BusinessException("The application context is null, please check.");
        } else {
            return CONTEXT.getBean(name, requiredType);
        }
    }

}
